from contextlib import asynccontextmanager

import uvicorn
from beanie import init_beanie
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

from API.AssetAPI import router as AssetRouter
from API.CommonAPI import router as CommonRouter
from API.UserAPI import router as UserRouter
from API.SyncAPI import router as SyncRouter
from DataModels.database import User, Asset, Sync
from config import client


@asynccontextmanager
async def lifespan(app: FastAPI):
    await init_beanie(
        database=client.Users,
        document_models=[User, Asset, Sync],
    )
    yield
    print("app closed")


app = FastAPI(lifespan=lifespan, docs_url="/api/docs")

origins = [
    "*",
    # "http://localhost",
    # "http://localhost:5173",
    # "http://localhost:8100"
]

# 后台api允许跨域
app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


@app.get("/")
async def root():
    return {"message": "Hello From ZaiWen User System API!"}


app.include_router(CommonRouter)
app.include_router(UserRouter)
app.include_router(AssetRouter)
app.include_router(SyncRouter)

if __name__ == "__main__":
    uvicorn.run(app="main:app", host="0.0.0.0", port=8000, reload=True)
